package com.demo.utils;

import java.io.UnsupportedEncodingException;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;

public class StringUtils {
	
	public static boolean isNotNullOrEmpty(String str){
		if(str!=null && !str.equals("") && !str.equals("null")){
			return true;
		}
		return false;
	}
	
	public static boolean isEmpty(String str){
		if(str==null){
			return true;
		}
		String str1 = str.replaceAll(" ", "");
		if(str1.equals("")){
			return true;
		}
		String str2 = str.toLowerCase();
		if(str2.equals("null") || str2.equals("empty") || str2.equals("undefined")){
			return true;
		}
		
		return false;
	}
	
	/**
	 * 
	  * 
	  * 文件大小转换
	  * 
	  *
	  * @author lixl
	  * @date 2016年5月27日${time}
	  * @param size
	  * @return
	 */
	public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
 
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else
            return String.format("%d B", size);
    }
	
	/**
	 * 
	 * @param request
	 * @return
	 */
	public static String getRemortIP(HttpServletRequest request) {
		String ip = request.getParameter("ip");
		if(ip==null || "".equals(ip)){
			if (request.getHeader("x-forwarded-for") == null) {
				ip = request.getRemoteAddr();
			}else{
				ip = request.getHeader("x-forwarded-for");
			}
		}
		
		return ip;
	}
	
	 public static String getRandomHString(int length) {
	        StringBuilder sb = new StringBuilder();
	        Random random = new Random();
	        int a = (int) (random.nextDouble()*length);
	        for(int i=0;i<a;i++){
	        	String str = "";
		        byte[] b = new byte[2];
		        int hightPos = (176 + Math.abs(random.nextInt(39)));
		        int lowPos = (161 + Math.abs(random.nextInt(93)));
		        b[0] = (Integer.valueOf(hightPos)).byteValue();
		        b[1] = (Integer.valueOf(lowPos)).byteValue();
		        try {
		            str = new String(b, "GBK");
		        } catch (UnsupportedEncodingException e) {
		        }
		        sb.append(str);
	        }
	        

	        return sb.toString();
	    }

}
